<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body :title="title" :width="width" @close="close">
    <!-- 插入代码 -->
    <template #footer>
      <el-button type="info" @click="close">取消</el-button>
      <el-button :disabled="isLoading" type="primary" @click="save">保存</el-button>
    </template>
  </vab-dialog>
</template>

<script lang="ts" setup>
import { api_getall, api_save } from '/@/api/obj_base'

//富文本引入开始
import { IDomEditor } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
const editorRef = shallowRef<IDomEditor | undefined>(undefined)
//富文本引入结束

defineOptions({
  name: 'ObjEdit',
})

const props = defineProps({
  width: {
    type: String,
    default: '518px',
  },
  span: {
    type: Number,
    default: 22,
  },
  rules: {
    type: Object,
    default: {
      name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
    },
  },
})

const emit = defineEmits(['fetch-data'])
const $baseMessage = inject<any>('$baseMessage')
const formRef = ref<any>(null)
const title = ref<string>('')
const dialogFormVisible = ref<boolean>(false)
const isLoading = ref(false)
let tablename = ''
const config_table = reactive<any>([]) //表配置
const cols = reactive<any>([]) //所有列
const edit_show = reactive<any>([]) //编辑列
const form = reactive<any>({})
const foreign_list = reactive<any>([])
const selection_list = reactive<any>([])
const status_list = reactive<any>([])
const img_list = reactive<any>([]) //特殊字段是图片的列

//自定义提交
// const rules = reactive<any>({
//   name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
//   // username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
// })

//富文本必备开始
const editorConfig = reactive<any>({
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '', // 您的服务器地址，注意：当前接口格式特殊与其他vab接口不同，请查看vip文档
      fieldName: 'vab-file-name',
      allowedFileTypes: ['image/*'],
      headers: {}, // 如需传递token请写到在这里
    },
  },
})

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}

// const handlePreview = () => {
//   dialogVisible.value = true
// }
//富文本必备结束

//上传图片必备  开始
const filelist = reactive<any>([])
const upload_img = (res: any, field: any) => {
  console.log('接收到了', res)
  if (field) {
    Object.assign(form[field], res)
  } else {
    Object.assign(filelist, res)
  }
}
const remove_img = (res: any, field: any) => {
  console.log('移出图片', res)
  if (field) {
    for (let i = 0; i < form[field].length; i++) {
      if (form[field][i].id == res.id) {
        form[field].splice(i, 1)
      }
    }
    Object.assign(form[field], res)
  } else {
    for (let i = 0; i < filelist.length; i++) {
      if (filelist[i].id == res.id) {
        filelist.splice(i, 1)
      }
    }
    Object.assign(filelist, res)
  }
}
//上传图片必备   结束

//自定义保存数据
const save = () => {
  console.log('save', form)
  isLoading.value = true
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const { msg }: any = await api_save(tablename, form)
      await $baseMessage(msg, 'success', 'hey')
      await close()
      dialogFormVisible.value = false
      isLoading.value = false
    }
  })
}
//通用外键变更
const foreignChange = ($event: any, model: any, field: any) => {
  console.log(model, $event, field)
  if (config_table.foreign_field[model] && config_table.foreign_field[model].next) {
    //表示有级联，去查对应表的数据
    const table = config_table.foreign_field[model].next
    getForeignList(table, $event, field, true)
  }
}
//通用根据外键ID获取对应数据
const getForeignList = (table: any, event: any, field: any, truncate: any) => {
  console.log(table, event, field)
  let search: any = {}
  search[field] = parseInt(event) > 0 ? parseInt(event) : 0
  search = JSON.stringify(search)
  api_getall(table, {
    search: search,
  }).then((res) => {
    //获取出来的结果赋值给对应级联表中
    const flist = foreign_list
    for (const key in flist) {
      if (key.startsWith(`${table}_T_`)) {
        //赋值筛选后的数据
        flist[`${key}`] = res.datalist
        //清空级联下级的值
        if (truncate) {
          form[key.replace(`${table}_T_`, '')] = ''
        }
      }
    }
  })
}
//通用显示弹窗
const showEdit = (res: any) => {
  console.log('showEdit', res)
  //外键
  Object.assign(foreign_list, res.foreign_list)
  Object.assign(selection_list, res.selection_list)
  if (res.config_table) {
    //编辑：外键
    tablename = res.config_table.tablename
    Object.assign(config_table, res.config_table)
    Object.assign(status_list, res.config_table.status_list)
    Object.assign(cols, res.config_table.cols)
    Object.assign(edit_show, res.config_table.edit_show)
    Object.assign(img_list, res.config_table.field_img)
    //判断是否有级联的外键，如果有，则去调用
    for (const key in res.config_table.foreign) {
      if (res.config_table.foreign[key].next) {
        getForeignList(
          res.config_table.foreign[key].next,
          res.detail[res.config_table.foreign[key].field],
          res.config_table.foreign[key].field
        )
      }
    }
  } else {
    //添加：外键
    tablename = res.tablename
    Object.assign(status_list, res.status_list)
    Object.assign(cols, res.cols)
    Object.assign(edit_show, res.edit_show)
    Object.assign(img_list, res.field_img)
    Object.assign(config_table, res)
  }

  //表示字段中有图片字段
  const imgObject: any = []
  //向字段里插入数据，否则无法写入
  for (const i in img_list) {
    imgObject[i] = []
  }
  Object.assign(form, imgObject)

  dialogFormVisible.value = true
  nextTick(() => {
    if (!res.detail) {
      title.value = '添加'
      Object.assign(form, {
        id: null,
      })
    } else {
      title.value = '编辑'
      //如果该表有状态，则需要讲状态转化为int类型
      if (res.detail.status) {
        res.detail.status = parseInt(res.detail.status)
      }
      Object.assign(form, res.detail)
    }
  })
}
defineExpose({
  showEdit,
})
//通用关闭弹窗
const close = () => {
  formRef.value.clearValidate()
  formRef.value.resetFields()
  dialogFormVisible.value = false
  emit('fetch-data')
}
</script>

<style lang="scss" scoped>
.el-col {
  margin: 5px 0;
}

.wang-editor-container {
  padding: 0 !important;
  // margin: -19px -19px 19px -19px;
  overflow: hidden !important;
  background: var(--el-background-color) !important;
  border: 0 !important;

  &.w-e-full-screen-container {
    z-index: 9999 !important;
  }

  .w-e-bar-divider {
    display: none;
  }

  .w-e-toolbar-init {
    border-bottom: 1px solid var(--el-border-color) !important;
  }

  .wang-editor-content {
    width: 70%;
    min-height: calc(var(--el-container-height) - 110px) !important;
    margin: 20px auto 20px auto;
    background-color: var(--el-color-white);
    border: 0;
  }

  #w-e-textarea-1 {
    margin: var(--el-margin) !important;
  }

  .wang-editor-footer {
    width: 70%;
    margin: auto;
  }

  @media (max-width: 768px) {
    .wang-editor-title,
    .wang-editor-content,
    .wang-editor-footer {
      width: 90%;
    }
  }
}

.wang-editor-dialog {
  img {
    max-width: 100%;
  }
}
</style>
